<script setup lang="ts">
import CopyOutlined from "@ant-design/icons-vue/CopyOutlined";
import {message, Modal} from "ant-design-vue";
import {WxtBiddingConstraintType, WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  promotionScene: {
    type: String as PropType<WxtBiddingConstraintType>,
    default: WxtBiddingConstraintType.促进全店成交,
  },
  data: {
    type: Array as PropType<any[]>,
    default: () => []
  }
});
const emit = defineEmits([
  "update:value",
  "next",
  "prev",
]);
const getPlansData = () => {
  try {
    return props.data.filter((item: any) => item.key === 'choicePlan')[0].value;
  } catch (e) {
    return [];
  }
}
const getKeywordData = () => {
  try {
    return props.data.filter((item: any) => item.key === 'addKeyword')[0].value;
  } catch (e) {
    return [];
  }
}
const getCreativeData = () => {
  try {
    return props.data.filter((item: any) => item.key === 'addCreative')[0].value;
  } catch (e) {
    return [];
  }
}
const getConfirmProductData = () => {
  try {
    return props.data.filter((item: any) => item.key === 'confirmProduct')[0].value;
  } catch (e) {
    return [];
  }
}
// 获取人群包数据
const getCrowdData = () => {
  try {
    return props.data.filter((item: any) => item.key === 'addAudience')[0].value;
  } catch (e) {
    return [];
  }
}
const columns = [
  {
    title: '计划名称',
    dataIndex: 'plan.campaignName',
    width: 240,
  },
  {
    title: '商品标题',
    dataIndex: 'product.title',
    dataType: 'custom',
    slot: 'productTitle',
  },
  ...(props.bizCode === WxtBizCode.关键字推广 ? [{
    title: '关键词数量',
    dataIndex: 'keyword',
    dataType: 'custom',
    slot: 'keywordCount',
    render: (text: any, record: any, index: number) => {
      return '关键词：' + record.requestData.adgroupList[0].wordList.length + '个  ' + '词包：' + record.requestData.adgroupList[0].wordPackageList.length + '个';
    }
  },
    {
      title: '人群数量',
      dataIndex: 'crowd',
      dataType: 'custom',
      slot: 'crowdCount',
      render: (text: any, record: any, index: number) => {
        return record.requestData.adgroupList[0].crowdList.length + '个';
      }
    },
    {
      title: '创意数量',
      dataIndex: 'creative',
      dataType: 'custom',
      slot: 'creativeCount',
      render: (text: any, record: any, index: number) => {
        return record.requestData.adgroupList[0].adgroupOcpc.enableOcpc ? 4 : 0 + '个';
      }
    }] : []),
  {
    title: '操作',
    dataType: 'custom',
    slot: 'action',
    width: 100,
  }
]
const creativeInfo = ref<any>({
  addAutoCreative: false,
  addMainPicVideo: false,
  addSystemBlackCreative: false,
  creativeIdList: [],
});
const creativeData = ref<any[]>([]);
const creativeFindRequire = () => {
  WxtUtils.customRequest('https://one.alimama.com/creative/findRequire.json', props.bizCode, {
    adgroupList: [
      ...props.data.filter((item: any) => item.key === 'choiceProduct')[0].value.map((item: any) => {
        return {
          material: item
        }
      })
    ],
    creativeOptimization: "black_creative",
    creativeSetMode: "professional",
    itemSelectedMode: "user_define",
    mainPicVideo: "1",
    optimizeTarget: 'shop_interest_new',
    promotionScene: "promotion_scene_crowd",
    promotionType: "item",
    subPromotionType: "item",
  }).then((res: any) => {
    creativeData.value = res.data.data.materialInfoList;
    calcDataSource();
  });
}
const dataSource = ref<any[]>([]);
const calcDataSource = () => {
  // 将计划和宝贝数据合并 product 放到plan products字段下
  const plansData = getPlansData();
  const keywordData = getKeywordData();
  const creativeData = getCreativeData();
  const confirmProductData = getConfirmProductData();
  const crowdData = getCrowdData();
  const data: any[] = [];
  plansData.forEach((plan: any) => {
    plan.products.forEach((product: any) => {
      data.push({
        id: `${plan.campaignId}-${product.itemId}`,
        plan: plan,
        product: product,
        keyword: keywordData,
        creative: creativeData,
        crowd: crowdData,
        requestData: {
          adgroupList: [{
            material: {
              materialId: product.itemId+'',
              materialName: product.title,
              promotionType: 'item',
              subPromotionType: 'item',
            },
            ...(props.bizCode === WxtBizCode.关键字推广 ? {
              adgroupOcpc: creativeData,
              crowdList: crowdData,
              dynamicTitleFlag: '1',
              wordList: [
                ...keywordData.autoWordList[product.itemId] || [],
                ...(keywordData.wordList[product.itemId] || []).map((keyword: any) => {
                  return {
                    bidPrice: keywordData.setting.bidPrice ?? (keywordData.setting.bidPriceRatio / 100).toFixed(2),
                    isManual: true,
                    matchScope: 4,
                    onlineStatus: 1,
                    originalWord: "",
                    word: keyword,
                  }
                }),
              ],
              wordPackageList: [
                {
                  "themeWordList": null,
                  "convRatio": null,
                  "relevanceType": null,
                  "wordPackageId": 0,
                  "bizCode": null,
                  "onlineStatus": 1,
                  "wordPackageType": 0,
                  "simpleWordList": null,
                  "bidPrice": keywordData.zhixuanSetting.bidPrice ?? (keywordData.zhixuanSetting.bidPriceRatio / 100).toFixed(2),
                  "strategyList": [
                    ...(keywordData.zhixuanSetting.options.includes("goodWord") ? [{
                      "strategyName": "好词优选",
                      "campaignId": null,
                      "bizCode": null,
                      "reasonTagList": [
                        {
                          "code": "auto_match",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "全网流量优选",
                          "type": null,
                          "tips": null,
                          "properties": null
                        },
                        {
                          "code": "auto_match",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "好词高效买",
                          "type": null,
                          "tips": null,
                          "properties": null
                        }
                      ],
                      "adgroupId": null,
                      "onlineStatus": 1,
                      "strategyId": 1,
                      "wordPackageType": null,
                      "reportInfoMap": null,
                      "bidPrice": keywordData.zhixuanSetting.bidPrice ?? (keywordData.zhixuanSetting.bidPriceRatio / 100).toFixed(2),
                      "reportInfoList": null
                    }] : []),
                    ...(keywordData.zhixuanSetting.options.includes("pickUp") ? [{
                      "strategyName": "捡漏",
                      "campaignId": null,
                      "bizCode": null,
                      "reasonTagList": [
                        {
                          "code": "marsh_land",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "性价比词圈选",
                          "type": null,
                          "tips": null,
                          "properties": null
                        },
                        {
                          "code": "marsh_land",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "好词辅助投",
                          "type": null,
                          "tips": null,
                          "properties": null
                        }
                      ],
                      "adgroupId": null,
                      "onlineStatus": 1,
                      "strategyId": 2,
                      "wordPackageType": null,
                      "reportInfoMap": null,
                      "bidPrice": keywordData.zhixuanSetting.bidPrice ?? (keywordData.zhixuanSetting.bidPriceRatio / 100).toFixed(2),
                      "reportInfoList": null
                    }] : []),
                    ...(keywordData.zhixuanSetting.options.includes("categoryOptimization") ? [{ // 类目优选
                      "strategyName": "类目优选",
                      "campaignId": null,
                      "bizCode": null,
                      "reasonTagList": [
                        {
                          "code": "category_preferred",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "类目常用对标",
                          "type": null,
                          "tips": null,
                          "properties": null
                        },
                        {
                          "code": "category_preferred",
                          "color": "#FF4D4D",
                          "bizCode": null,
                          "iconType": null,
                          "icon": null,
                          "name": "同行都在买",
                          "type": null,
                          "tips": null,
                          "properties": null
                        }
                      ],
                      "adgroupId": null,
                      "onlineStatus": 1,
                      "strategyId": 3,
                      "wordPackageType": null,
                      "reportInfoMap": null,
                      "bidPrice": keywordData.zhixuanSetting.bidPrice ?? (keywordData.zhixuanSetting.bidPriceRatio / 100).toFixed(2),
                      "reportInfoList": null
                    }] : []),
                  ],
                  "wordTotalPermeabilityUv": null,
                  "reasonTagList": null,
                  "mPenetrationRate": null,
                  "recReason": null,
                  "multiFactor": null,
                  "shopWordPermeabilityUv": null,
                  "impression": null,
                  "wordPackageName": "流量智选",
                  "status": 1
                },
                ...keywordData.wordPackageList.filter((item: any) => item.item.itemId === product.itemId && item.plan.campaignId === plan.campaignId).map((pack: any) => {
                  // 去掉不需要的字段 item 和plan
                  const {
                    item,
                    plan,
                    ...rest
                  } = pack;
                  return rest;
                })
              ]
            } : {}),
            ...(props.bizCode === WxtBizCode.精准人群推广 ? {
              clickUrlCreativeTemplateInfos: [],
              creativeInfo:{...creativeInfo,
                materialImageInfoList:creativeData.filter((i)=>i.materialId === product.itemId),
              },
              creativeTemplateInfos: [
                {
                  "adzoneName": "首页焦点图",
                  "templateName": "默认模板",
                  "templateImg": "https://img.alicdn.com/imgextra/i2/O1CN01Hr1RRA1tNDBbyOZfz_!!6000000005889-2-tps-684-998.png",
                  "templateId": 330016,
                  "previewHtml": "<img src=\"https://img.alicdn.com/imgextra/i2/O1CN01Hr1RRA1tNDBbyOZfz_!!6000000005889-2-tps-684-998.png\"/>"
                },
                {
                  "adzoneName": "猜你喜欢信息流",
                  "templateName": "默认模板",
                  "templateImg": "https://img.alicdn.com/imgextra/i2/O1CN01DQMXpn1hVf6Y9g3ts_!!6000000004283-2-tps-342-550.png",
                  "templateId": 327624,
                  "previewHtml": "<img src=\"https://img.alicdn.com/imgextra/i2/O1CN01DQMXpn1hVf6Y9g3ts_!!6000000004283-2-tps-342-550.png\"/>"
                },
                {
                  "adzoneName": "全屏微详情",
                  "templateName": "默认模板",
                  "templateImg": "https://img.alicdn.com/imgextra/i3/O1CN01hLr4Vy1EcQ7aZc3Lt_!!6000000000372-2-tps-750-1624.png",
                  "templateId": 345206,
                  "previewHtml": "<img src=\"https://img.alicdn.com/imgextra/i3/O1CN01hLr4Vy1EcQ7aZc3Lt_!!6000000000372-2-tps-750-1624.png\"/>"
                }
              ],
            } : {})
          }],
          campaign:
              {
                campaignId: plan.campaignId+'',
                shieldItems:[WxtBizCode.关键字推广,WxtBizCode.精准人群推广].includes(props.bizCode) ? undefined : null,
              }
        },
        status: 0, // 0 等待添加 1 添加中 2 添加成功 3 添加失败
        message:
            '', // 添加失败的原因
      })
      ;
    });
  });
  dataSource.value = data;
  emit('update:value', data);
}
if (props.bizCode === WxtBizCode.精准人群推广) {
  calcDataSource();
}else {
  creativeFindRequire();
}
const copy = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    message.success('复制成功')
  }).catch(() => {
    message.error('复制失败')
  });
}
const next = () => {
  Modal.confirm({
    title: '提示',
    content: '下一步将自动批量添加商品，是否继续？',
    onOk: () => {
      emit('update:value', dataSource.value);
      emit('next', dataSource.value);
    }
  })
}
</script>

<template>
  <base-table table-name="批量添加商品-用户确认" :columns="columns" :data-source="dataSource" :scroll="{
    y: 500,
  }"
  >
    <template #productTitle="row">
      <a-row type="flex" class="adgroupName" :gutter="5">
        <a-col>
          <a-popover placement="right">
            <template #content>
              <img :src="row.product.imgUrl"
                   style="width: 200px;height: 200px;"
              />
            </template>
            <img :src="row.product.imgUrl"
                 style="width: 60px;height: 60px;border-radius: 5px;"
            />
          </a-popover>
        </a-col>
        <a-col flex="1" class="title">
          <a-tooltip :title="row.product.title">
              <span style="
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            line-clamp: 2;
            -webkit-box-orient: vertical;"
              >{{ row.product.title }}</span>
          </a-tooltip>
          <div>
            <a-space>
              <span style="color: #666;">ID: {{ row.product.itemId }}</span>
              <CopyOutlined style="color: #1677ff;cursor: pointer;font-size: 12px;" @click="copy(row.product.itemId)"/>
            </a-space>
          </div>
        </a-col>
      </a-row>
    </template>

    <template #keywordCount="row">
      <a-row type="flex" class="adgroupName" :gutter="5">
        <a-col flex="1" class="title">
          <a-space>
            <a-tooltip :title="(row.requestData.adgroupList[0].wordList||[]).map((i)=>{
              return i.word
            }).join(',')"
            >
              <span style="color: #666;">{{
                  (row.requestData.adgroupList[0].wordList || []).length || 0
                }} 个关键词</span>
            </a-tooltip>
            <a-tooltip :title="(row.requestData.adgroupList[0].wordPackageList||[]).map(i=>{
              return i.wordPackageName;
            }).join(',')"
            >
            <span style="color: #666;"
            >{{
                (row.requestData.adgroupList[0].wordPackageList || []).length || 0
              }} 个词包</span>
            </a-tooltip>
          </a-space>
        </a-col>
      </a-row>
    </template>
    <template #crowdCount="row">
      <a-space>
        <a-tooltip :title="(row.requestData.adgroupList[0].crowdList||[]).map((i)=>{
              return i.crowd.crowdName
            }).join(',')"
        >
              <span style="color: #666;">{{
                  (row.requestData.adgroupList[0].crowdList || []).length || 0
                }} 个人群包</span>
        </a-tooltip>
      </a-space>
    </template>
    <template #creativeCount="row">
              <span style="color: #666;">{{
                  row.requestData.adgroupList[0].adgroupOcpc.enableOcpc ? 4 : 0 + '个'
                }}个创意</span>
    </template>
    <template #action="row">
      <a-space>
        <a-button type="primary" danger size="small" @click="()=>{
          // 从dataSource删除当前宝贝
          dataSource = dataSource.filter((item)=>item.id !== row.id);
        }"
        >删除
        </a-button>
      </a-space>
    </template>
  </base-table>
  <a-divider style="margin-top: 10px;"/>
  <a-row type="flex">
    <a-col flex="1">
    </a-col>
    <a-col>
      <a-space>
        <a-button @click="emit('prev',[])">上一步</a-button>
        <a-button type="primary" @click="next">下一步</a-button>
      </a-space>
    </a-col>
    <a-col flex="1">
    </a-col>
  </a-row>
</template>

<style scoped>

</style>
